package system

import (
	"github.com/gin-gonic/gin"
	"seven-admin/app/admin/schemas/query"
	"seven-admin/app/admin/schemas/req"
	"seven-admin/app/admin/service/system"
	"seven-admin/app/middleware"
	"seven-admin/core"
	"seven-admin/core/response"
	"seven-admin/util"
)

var TenantGroup = core.Group("/system", newTenantHandler, regTenant, middleware.TokenAuth())

func newTenantHandler(srv system.AuthTenantService) *tenantHandler {
	return &tenantHandler{srv: srv}
}

func regTenant(rg *gin.RouterGroup, group *core.GroupBase) error {
	return group.Reg(func(handle *tenantHandler) {
		rg.GET("/tenant/all", handle.all)
		rg.GET("/tenant/list", middleware.RecordLog("租户列表"), handle.list)
		rg.GET("/tenant/detail", middleware.RecordLog("租户详情"), handle.detail)
		rg.POST("/tenant/add", middleware.RecordLog("租户新增"), handle.add)
		rg.POST("/tenant/edit", middleware.RecordLog("租户编辑"), handle.edit)
		rg.POST("/tenant/del", middleware.RecordLog("租户删除"), handle.del)
	})
}

type tenantHandler struct {
	srv system.AuthTenantService
}

// all 租户所有
func (rh tenantHandler) all(c *gin.Context) {
	res, err := rh.srv.All(query.GetAuthReq(c))
	response.CheckAndRespWithData(c, res, err)
}

// list 租户列表
func (rh tenantHandler) list(c *gin.Context) {
	var page req.PageReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyQuery(c, &page)) {
		return
	}
	res, err := rh.srv.List(page, query.GetAuthReq(c))
	response.CheckAndRespWithData(c, res, err)
}

// detail 租户详情
func (rh tenantHandler) detail(c *gin.Context) {
	var detailReq req.IdReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyQuery(c, &detailReq)) {
		return
	}
	res, err := rh.srv.Detail(detailReq.ID, query.GetAuthReq(c))
	response.CheckAndRespWithData(c, res, err)
}

// add 新增租户
func (rh tenantHandler) add(c *gin.Context) {
	var addReq req.SystemAuthTenantAddReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyJSON(c, &addReq)) {
		return
	}
	response.CheckAndResp(c, rh.srv.Add(addReq, query.GetAuthReq(c)))
}

// edit 编辑租户
func (rh tenantHandler) edit(c *gin.Context) {
	var editReq req.SystemAuthTenantEditReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyJSON(c, &editReq)) {
		return
	}
	response.CheckAndResp(c, rh.srv.Edit(editReq, query.GetAuthReq(c)))
}

// del 删除租户
func (rh tenantHandler) del(c *gin.Context) {
	var delReq req.IdReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyJSON(c, &delReq)) {
		return
	}
	response.CheckAndResp(c, rh.srv.Del(delReq.ID, query.GetAuthReq(c)))
}
